﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using System.Windows.Forms;
using Neo4jClient;
using Neo4jClient.Cypher;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WinFormsApp1.Neo4JForms
{
    public partial class Neo4JViewForms : UserControl
    {
        public Neo4JViewForms()
        {
            InitializeComponent();
        }

        private BoltGraphClient BuildClient()
        {
            // 初始化 Neo4j 客户端
            var client = new BoltGraphClient(new Uri($"bolt://{this.textBox1.Text}:{this.textBox4.Text}"), this.textBox2.Text, this.textBox3.Text);
            client.ConnectAsync().Wait();

            return client;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var client = BuildClient();

                this.listBox1.Items.Clear();

                // Neo4j 没有表的概念，通常使用标签（Labels）来组织数据，这里查询所有的标签名
                var result = client.Cypher.Match("(n)")
                                        .ReturnDistinct(n => n.Labels())
                                        .ResultsAsync.Result;

                var allLabels = new List<string>();
                foreach (var labels in result)
                {
                    allLabels.AddRange(labels);
                }
                var uniqueLabels = allLabels.Distinct().ToList();

                // 这里可以添加处理标签名的逻辑，例如显示在界面上
                // 示例：将标签名输出到控制台
                foreach (var label in uniqueLabels)
                {
                    this.listBox1.Items.Add(label);
                }

                client.Dispose();
            }
            catch (Exception ex)
            {
                // 处理异常
                MessageBox.Show($"连接或查询 Neo4J 数据库时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Neo4JViewForms_Load(object sender, EventArgs e)
        {
            this.listBox1.SelectedIndexChanged += ListBox1_SelectedIndexChanged;
        }

        private void ListBox1_SelectedIndexChanged(object? sender, EventArgs e)
        {

            var tableName = this.listBox1.SelectedItem.ToString();

            GetEntities(tableName);

            GetRelations(tableName);
        }

        private void GetRelations(string tableName)
        {
            Neo4JTableReader reader = new Neo4JTableReader()
            {
                TableName = tableName,
                Client = BuildClient()
            };
            var dt = reader.GetRelationsAsDataTable();
            this.dataGridView2.DataSource = dt;

            if (m_allEntityCount.ContainsKey(tableName) == false)
            {
                m_allEntityCount.Add(tableName, dt.Rows.Count);
            }
            else
            {
                m_allEntityCount[tableName]= dt.Rows.Count;
            }
            toolStripLabelRelationCount.Text = "关系数量:" + dt.Rows.Count+"/"+ m_allEntityCount.Values.ToList().Sum();

            reader.Client.Dispose();
        }

        private void GetEntities(string tableName)
        {
            Neo4JTableReader reader = new Neo4JTableReader()
            {
                TableName = tableName,
                Client = BuildClient()
            };
            var dt = reader.GetEntities();
            this.dataGridView1.DataSource = dt;
            if (m_allRelationCount.ContainsKey(tableName) == false)
            {
                m_allRelationCount.Add(tableName, dt.Rows.Count);
            }
            else
            {
                m_allRelationCount[tableName] = dt.Rows.Count;
            }
            toolStripLabelEntityCount.Text = "实体数量:" + dt.Rows.Count + "/" + m_allRelationCount.Values.ToList().Sum();

            reader.Client.Dispose();
        }

        private Dictionary<string, int> m_allEntityCount = new Dictionary<string, int>();
        private Dictionary<string, int> m_allRelationCount =new Dictionary<string, int>();

        private async void button2_ClickAsync(object sender, EventArgs e)
        {
            try
            {
                string label = this.listBox1.SelectedItem as string;
                if (MessageBox.Show("是否删除[" + label + "]的数据?", "删除", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
                var client = BuildClient();
                await client.Cypher
                .Match($"(n:{label})")
                .DetachDelete("n")
                .ExecuteWithoutResultsAsync();
                MessageBox.Show("成功");
            }
            catch (Exception err)
            {
                MessageBox.Show($"删除 Neo4J 数据库时出错: {err.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        
    }

}
